/**
 * @description 表单序列化，支持参数trimFlag, 是否需要去除值两边的空格
 * 注:对于input type="hidden"的情况有时不能成功封装进来，有需要可以改成input style=display:none即可正常
 */
;(function($,window,document,undefined){
    $.fn.serializeJson=function(trimFlag){
    	var trimOption = true;
    	if(trimFlag){
    		trimOption = trimFlag;
    	}
        var serializeObj={};  
        var array=this.serializeArray();
        $(array).each(function(){  
        	var v = this.value;
        	if(trimOption===true){
        		v = $.trim(v);
        	}
            if(serializeObj[this.name]){  
                if($.isArray(serializeObj[this.name])){ 
                    serializeObj[this.name] += "," + v;
                }else{
                	serializeObj[this.name] += "," + v;
                }  
            }else{  
                serializeObj[this.name]=v;
            }  
        });  
        return serializeObj;  
    };  
})(jQuery,window,document);


//格式化输入字符串,去除两头空格,正常情况下$.trim()够用
function getNoSpaceData(data) {
	data = $.trim(data);
	if(data.length!=0){
		while(data.substring(0,1)=="\u0000"){
			data=data.substring(1);
			data = $.trim(data);
		}
		while(data.substring(length-1)=="\u0000"){
			data = data.substring(0,length-1);
			data = $.trim(data);
		}
	}
	return data;
}


/**
 * @description 
 * 注：这里传入的imageFile需要指定名称, 默认存放在source里面，如果没有source属性，或者source属性为空，则默认上传文件后台接收对象名称为uploadFile
 * imageFile 图片对象
 * photoBase64Arr存放图片base64的对象
 * base64字符串为source值
 * base64文件类型为(扩展名)source+"Ext"
 * imageSrc: 如果需要回填image到对应的<image>里面，则对应的img标签的id
 * 用例：定义一个对象 obj， var obj ={},
 * 	   设置对象的source属性为file控件的name值(如果无特殊需求可以不填，则默认名字为uploadFile)-obj.source=file.name
 * 	   调用公共方法$.imageToBase64(file,user,"pic1(选填)",function(){ dosomething}(选填));
 */
;(function($,window,document,undefined){  
    $.imageToBase64 =function(imageFile,photoBase64Arr,imageSrc,callback){
    	//如果没有设置source,即file控件的名称,则默认叫uploadFile
    	if(!imageFile.source){
    		imageFile.source ="uploadFile";
    	}
    	var base64Image;
        //定义默认的图片长度及宽度
    	var maxImageHeight = 600;
        var maxImageWidth = 800;
        var reader = new FileReader();
        reader.onload = function(){
        	var image = new Image();
        	image.onload=function(){
        		var canvas = document.createElement('canvas');
        		var originWidth=image.width;
        		if(originWidth>maxImageWidth){
        			image.width = originWidth*(maxImageWidth/originWidth);
        			image.height = image.height*(maxImageWidth/originWidth);
        		}
        		var originHeight=image.height;
        		if(originHeight>maxImageHeight){
        			image.width = image.width*(maxImageHeight/originHeight);
        			image.height = originHeight*(maxImageHeight/originHeight);
        		}
        		canvas.width = image.width;
    			canvas.height = image.height;
    			var ctx =canvas.getContext('2d').drawImage(image, 0, 0,image.width, image.height); // 将图像绘制到canvas上  
    			var fileSize =imageFile.size;
    			if(fileSize/1024 >400){    				
    				base64Image = canvas.toDataURL(imageFile.type,400*1024/fileSize);
    			}else{
    				base64Image = canvas.toDataURL(imageFile.type);
    			}
    			if(imageSrc){
    				$('#'+imageSrc).attr('src',base64Image);
    			}
    			base64Image = base64Image.replace(/^data:image\/[a-zA-z]+;base64,/,"");
    			photoBase64Arr[imageFile.source]= base64Image;
    			photoBase64Arr[imageFile.source+"Ext"]=imageFile.name.substring(imageFile.name.indexOf(".")+1);
//    			如果有回调函数，则执行
    			if(callback && typeof(callback) == 'function'){
    				callback();
    			}
        	};
        	image.src = this.result;
        };
        reader.readAsDataURL(imageFile);
    };  
})(jQuery,window,document);

/**
 * 重置easyui表单 后来发现$('#'+formId).form('reset')就可以了，暂时不用
 */
function resetForm(options){
	var defaults = {
		formId:'', //表单id
		noResetId:'', //勿需重置的控件id
	};
	if(options){
		defaults = $.extend({},defaults,options);
	}
	if(defaults.noResetId){
		var arr= noResetId.split(',;:|');
		for(var i in arr){
			$('#'+arr[i]).attr('value',$('#'+arr[i]).val());
		}		
	}
	if($('#'+defaults.formId)[0]){		
		//$('#'+defaults.formId)[0].reset();
		//easyUI 重置表单
		$('#'+defaults.formId).form('reset');
	}
	if(defaults.noResetId){
		var arr= noResetId.split(',;:|');
		for(var i in arr){
			$('#'+arr[i]).val($('#'+arr[i]).attr('value'));
			$('#'+arr[i]).removeAttr('value');
		}		
	}
}


/**
 * @param option
 * @description 封装ajax提交数据
 */
function postAjax(option) {
	var defaultOption = {
		url : "",
		type : "POST",
		data : null,
		callback : null,
		datatype : "json",
		async : true,
		contentType : "",
		errorCallback : false
	};

	option = $.extend(defaultOption, option);

	if (option.contentType == "json") {
		option.contentType = "application/json; charset=utf-8";
	} else {
		option.contentType = "application/x-www-form-urlencoded;charset=UTF-8";
	}

	if (option.url == "") {
		$.messager.confirm('提示', 'url不能为空!', function(r){
			//console.log(r);
		});
		return;
	}
	
	$.ajax({
		type : option.type,
		data : option.data,
		async : option.async,
		dataType : option.datatype,
		contentType : option.contentType,
		url : option.url,
		success : function(result) {
			// 成功返回后的操作
			if (option.callback != null) {
				option.callback(result);
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			// 成功返回后的操作
			if (option.callback != null) {
				option.callback(null);
			}
		},
		complete : function() {
		}
	});
}

/**
 * @param name
 * @param value
 * @param obj
 * @description 将数据打包进json
 */
function toJson(name,value,obj){
	if(!obj){
		obj={};
	}
	obj[name]=value
	return obj;
}

/**
 * @description 通用消息回显框
 */
function commonShow(result){
	if(result){
		if(typeof(result) == 'string'){
			$.messager.alert('提示', result);
		}else if(result.status || typeof(result.status) == 'number'){			
			if(result.status==1){
				$.messager.show({
					title:'提示', 
					msg:(result && result.msg)?result.msg:'操作成功!',
							timeout:1500,
				});
			}else{
				$.messager.alert('提示', (result && result.msg)?result.msg:'操作失败', function(r){
				});
			}
		}
	}
}
/**
 * @param obj
 * @param value
 * @descriiption easyui填充数据
 */
function fullfillForm(obj,value){
	if(obj && obj.length>0){
		var sheetType=obj[0].type;
		if(sheetType){
			if(!obj.attr('class') || obj.attr('class').indexOf("easyui")<0){
				obj.val(value);
			}else if('text'==sheetType){
				obj.textbox('setValue',value);
			}else if(sheetType.indexOf('select')>=0){
				obj.combobox('setValue',value);
			}
		}
	}
}

/**
 * @description easyui数据表格统一初始化
 * @param options
 * @returns
 */
function commonDataGrid(options){
	var option = {
		url:'',
		gridId:'datagrid',//默认是这个id的,可以根据实际修改
		columns:[[]],
		striped:true,
		loadMsg:'数据加载中请稍后……',
		formerGrid:'',//已经初始化的表格(用于安装设备表格和维修设备表格的切换,暂时用不到)
		beforeLoad:undefined,
		title:'',
		fitColumns:true,
		fit:true,
	};
	var gridOption = $.extend({},option,options);
	if(!option.gridId){
		commonShow('表格对象不存在');
		return;
	}else{
		var dataGrid = $('#'+option.gridId).datagrid(gridOption);
		/**
		 * gridOption
		var dataGrid = $('#'+option.gridId).datagrid({
		   pagination:true,//显示分页  
		   pageSize:50,//分页大小  
		   singleSelect:true,   
		   pageList:[50,100,150,200],//每页的个数  
		   fit:option.fit,//自动补全  
		   fitColumns:option.fitColumns,
		   url:option.url,
		   striped:true,
		   queryParams:option.queryParams,//一开始为空，搜索后赋值
		   //iconCls:"icon-save",//图标  
		   title:option.title,   
		   columns:option.columns,
		   onBeforeLoad: option.beforLoad,
		});
				 */
		options.formerGrid=option.gridId;
	}
	return dataGrid;
}


function formPost(options){
	var defaults={
		url:'',
		data:undefined
	};
	var option= $.extend({},defaults,options);//
	var url= option.url;
	var data = option.data;
	if(!url){
		commonShow('url不能为空');
		return;
	}else if(data && typeof(data)!= 'object'){
		commonShow('传入数据需要为键值对格式');
		return;
	}
	
	var iframe = document.createElement("iframe");
	iframe.name='hiddenframe';	
	document.body.appendChild(iframe);
	
	var postForm = document.createElement("form");//创建form表单
	postForm.method = "post";
	postForm.action = url;
	postForm.target = '';
	for(var i in data){
		var queryInput = document.createElement("input");	
		queryInput.setAttribute("name", i);
		queryInput.setAttribute("value", data[i]);
		postForm.appendChild(queryInput);		
	}
	document.body.appendChild(postForm);
	postForm.submit();
	//iframe.contentWindow.document.body.appendChild(postForm);
	document.body.removeChild(iframe);
	document.body.removeChild(postForm);
}

function resetFormByFormid(formId){
	$('#'+formId).form('reset');
}


function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

function isEmpty(str){
	return (str == undefined) || (str == null) || (str == "null") || (($.trim(str)).length == 0);
}
function createHtmlElement(type,elementName,elementId){
	var element = document.createElement(type);
	if(elementName){
		element.name= elementName;
	}
	if(elementId){
		element.id = elementId;
	}
	return element;
}
Date.prototype.format = function(format){
 var o = {
	 "M+" : this.getMonth()+1, //month
	 "d+" : this.getDate(),    //day
	 "h+" : this.getHours(),   //hour
	 "m+" : this.getMinutes(), //minute
	 "s+" : this.getSeconds(), //second
	 "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
	 "S" : this.getMilliseconds() //millisecond
 }
 if(/(y+)/.test(format)) format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
 for(var k in o){	 
	 if(new RegExp("("+ k +")").test(format))
		 format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k]:("00"+ o[k]).substr((""+ o[k]).length));
 }
 return format;
}

/**
 * 改变panel、datagrid大小
 */
function datagridResize(datagridId){
	var v1 = 90;
	var v2 = 80;
	queryDivResize(datagridId);
	if($('#baseQueryTab').height()){
		var baseQueryTabHeight = $('#baseQueryTab').height();
		v1 = baseQueryTabHeight + 20;
		v2 = baseQueryTabHeight + 10;
	}
	if($('#moreQueryTab').height() && !$('#moreQueryTab').is(':hidden')){
		var tabHeight = $('#moreQueryTab').height();
		v1 = v1 + tabHeight;
		v2 = v2 + tabHeight;
	}
	$('#pageListPanel').panel("resize", {
		height: $(window).height() - v1
    });
    $('#' + datagridId).datagrid("resize", {
    	height: $(window).height() - v2
    });
    queryDivResize(datagridId);
}
/**
 * 改变查询条件DIV大小
 */
function queryDivResize(datagridId){
	var dataGridHeight = $('#' + datagridId).datagrid('options').height;
	$('#queryDiv').panel("resize", {
		height: $(window).height() - dataGridHeight - 5
    });
}
function openWindows(id) {
    var $win = $('#' + id).window({});
    $win.window('hcenter');
    $win.window('open');
}

/**
 * 弹出加载层
 * @param showWords		加载层显示的文字
 */
function load(showWords) {  
	if(!showWords || showWords == ''){
		showWords = '正在加载，请稍候...';
	}
    $("<div class=\"datagrid-mask\" style='z-index: 99998'></div>").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body");
    $("<div class=\"datagrid-mask-msg\"  style='z-index: 99999'></div>").html('<font style="font-size:12px;">'+showWords+'</font>').appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 });
}
//关闭加载层
function disLoad() {  
    $(".datagrid-mask").remove();  
    $(".datagrid-mask-msg").remove();  
}
//设置默认查询时间
function setInitDate() {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() > 8 ? date.getMonth() + 1 : "0"
      + (date.getMonth() + 1);
  var day = date.getDate() > 8 ? date.getDate() : "0"
      + (date.getDate());
  $('#startTime').val(year + "-" + month + "-" + "01" + " 00:00:00");
  $('#endTime').val(year + "-" + month + "-" + day + " 23:59:59");
}
function getJsonObj() {
	var reJson = {};
	var fields = $(":input").serializeArray();
	jQuery.each(fields, function(i, field) {
		if (field.type != "button" || field.type != "img") {
			reJson[field.name + ""] = field.value;
		}
	});
	return reJson;
}
